package cc.magicjson.design.principles.openclose;

import org.springframework.util.StopWatch;

import java.util.*;

public class Vote {
    private String five;
    private String three;
    private String one;

    public Vote(String five, String three, String one) {
        this.five = five;
        this.three = three;
        this.one = one;
    }

    public String getFive() {
        return five;
    }

    public String getThree() {
        return three;
    }

    public String getOne() {
        return one;
    }
    public static List<String> getSortedCandidates(List<Vote> votes) {
        Map<String, Integer> scoreMap = new HashMap<>();
        // 计算每个候选人的总分数
        for (Vote vote : votes) {
            scoreMap.put(vote.getFive(), scoreMap.getOrDefault(vote.getFive(), 0) + 5);
            scoreMap.put(vote.getThree(), scoreMap.getOrDefault(vote.getThree(), 0) + 3);
            scoreMap.put(vote.getOne(), scoreMap.getOrDefault(vote.getOne(), 0) + 1);
        }
        // 将候选人及其分数存入一个列表
        List<Map.Entry<String, Integer>> candidates = new ArrayList<>(scoreMap.entrySet());
        // 对候选人进行排序
        candidates.sort((e1, e2) -> {
            int scoreComparison = e2.getValue().compareTo(e1.getValue());
            if (scoreComparison != 0) {
                return scoreComparison;
            } else {
                return e1.getKey().compareTo(e2.getKey());
            }
        });
        // 提取排序后的候选人名字
        List<String> sortedCandidates = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : candidates) {
            sortedCandidates.add(entry.getKey());
        }
        return sortedCandidates;
    }

    public static void main(String[] args) {
        List<Vote> list = Arrays.asList(
            new Vote("Ford", "Bob", "Anna"),
            new Vote("Ford", "Bob", "Anna"),
            new Vote("Ford", "Bob", "Harry"),
            new Vote("Bob", "Ford", "Harry")
        );

        List<String> sortedCandidates = getSortedCandidates(list);
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        StringJoiner stringJoiner = new StringJoiner(", ", "[", "]");
        sortedCandidates.forEach(stringJoiner::add);
        stopWatch.stop();

        System.out.println(sortedCandidates);
        System.out.println(stringJoiner);
        System.out.println(stopWatch.getTotalTimeNanos());
    }
}
